

const Koa = require('koa');

const fs = require('fs');
const iconv = require('iconv-lite'); 

const app = new Koa();

async function route(url) {
    
    let page = '404.html';
    switch(url) {
        case '/':
            page = 'index.html';
            break;
        case '/index':
            page = 'index.html';
            break;
        case '/404':
            page = '404.html';
            break;
        default:
            break;
    }

    let html = await render(page)

    return html
}

function render(page){
    return  new Promise((resolve,reject)=>{
        let pageUrl = `./page/${page}`;
        // fs.readFile(pageUrl,"binary",(err,data)=>{
        //     if(err){
        //         reject(err)
        //     }else{
        //         resolve(iconv.decode(data, 'gbk'));
        //     }
        // })
        resolve(fs.createReadStream(pageUrl));
    })
}

app.use( async (ctx) => {
    // 获取原生路由、实现路由功能
    let url = ctx.request.url
    let html = await route(url)
    ctx.type = 'text/html'
    ctx.body = html
    // ctx.body = fs.createReadStream('./page/index.html');
})

app.listen(3000, () => {
    console.log('koa server starting demo4.js')
})